package com.winchain.provider.expiration.cmd;

import com.shell.bee.persistence.transaction.Transaction;
import com.shell.bee.persistence.transaction.TransactionUtil;
import com.shell.framework.command.CommandContext;
import com.shell.framework.command.ICommand;
import com.shell.framework.utils.CommonDataUtil;
import com.shell.framework.utils.SysDateUtil;
import com.winchain.basic.exception.ExtException;
import com.winchain.chainbill.ChainBillUtil;
import com.winchain.provider.expiration.po.CbDebit;
import com.winchain.provider.expiration.rx.BillExpirationEvent;
import com.winchain.provider.expiration.service.CbDebitService;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class BillExpDebitExeCmd implements ICommand<BillExpirationEvent> {
	protected final Log logger = LogFactory.getLog(getClass());
	@Autowired
	private CbDebitService cbDebitService;

	public boolean execute(CommandContext<BillExpirationEvent> context) throws Exception {
		BillExpirationEvent event = (BillExpirationEvent) context.getSource();
		String expDate = event.getDate();
		String grpId = event.getGrpId();
		if ("single".equals(ChainBillUtil.getExpSettleMode(grpId))) {
			return true;
		}
		List<CbDebit> cbDebits = this.cbDebitService.selectDebitBill(expDate, grpId, new String[] { "0" });
		for (final CbDebit cbDebit : cbDebits) {
			try {
				TransactionUtil.execute(new Transaction() {
					public void doInTransaction() {
						CbDebit debit = BillExpDebitExeCmd.this.cbDebitService.selectAndLockByKey(cbDebit.getDebitId());
						if (!cbDebit.getDebitState().equals(debit.getDebitState())) {
							BillExpDebitExeCmd.this.logger.warn("Debit state Has Changed.");
							return;
						}
						String txAbs = "�������� - ������������";
						List<String> abnormalMsgs = BillExpDebitExeCmd.this.cbDebitService.pmt(debit, txAbs);
						if (abnormalMsgs.size() == 0) {
							debit.setDebitState("1");
							debit.setActualAmount(debit.getBillAmount());
							debit.setSettleDate(debit.getDebitDate());
						} else {
							debit.setDebitState("2");
							BillExpDebitExeCmd.this.cbDebitService.sendExpDebitFailedMessage(debit);
						}
						debit.setEditorId(CommonDataUtil.getUserId());
						debit.setEditTime(SysDateUtil.getSystemDateTime());
						BillExpDebitExeCmd.this.cbDebitService.updateNotNull(debit);
					}
				}, new int[0]);
			} catch (Exception e) {
				e.printStackTrace();
				this.logger.error(getClass() + "��������", e);
				throw new ExtException(e.getMessage());
			}
		}
		return false;
	}
}
